<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Exceptions\ApiException;
use App\Models\Images;
use Illuminate\Support\Facades\Storage;

class ImageService
{
    public function upload($file): string
    {
        $file_arr = explode('.', $file->getClientOriginalName());

        $disk = Storage::disk('cosv5');
        $path = $disk->put('images', $file);
        return substr($disk->url($path), 0, strrpos($disk->url($path), '?sign=q-sign-algorithm'));
    }

    public function create(string $url, string $title, int $render_mode)
    {
        $check_name = Images::query()->where(['title' => $title])->first();
        if ($check_name) {
            throw new ApiException('图片名称重复');
        }
        Images::query()->create([
            'url' => $url,
            'title' => $title,
            'render_mode' => $render_mode,
        ]);
        return true;
    }

    public function update(int $id, int $render_mode): bool
    {
        Images::where('id', $id)
            ->update(['render_mode' => $render_mode]);
        return true;
    }

    public function delete(int $id)
    {
        $image_url = Images::query()->find($id);
        if ($image_url) {
            $disk = Storage::disk('cosv5');
            $disk->delete($image_url->url);
            $image_url->delete();
        }
        return true;
    }

    public function getList($page, $pageSize, $search): array
    {
        $builder = Images::query();

        if (isset($search['title'])) {
            $builder->where('title', 'like', '%' . $search['title'] . '%');
        }

        $count = $builder->count();

        $list = $builder
            ->orderByDesc('id')
            ->skip(($page - 1) * $pageSize)->take($pageSize)->get();
        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }
}
